#!/opt/chef/embedded/bin/ruby


# This script can be used to loginto one specific machine named by role...
# doesn't handle collapsed roles well.

require 'optparse'
require 'json'
require 'erubis'

dname = ARGV[0]
keyfileloc = ARGV[1]
roleid = ARGV[2]
userid= ARGV[3]

def usage(exitcode)
    puts "Usage:  scripts/loginto.rb <deployment-name> <private-key-file> <role> [userid]"
    exit exitcode
end

if ( dname == nil  )
    puts "Please provide a deployment name."
    usage(1)
end

if ( keyfileloc == nil  )
    puts "Please provide keyfile location."
    usage(2)
end

if ( roleid == nil ) 
	puts "Please provide a role."
end

if ( userid == nil ) 
	userid="idcuser"
end

if ( ! File.file?("deployments/conf/#{dname}.json"))
    puts "Deployment file does not exist ./deployments/conf/#{dname}.json"
    usage(4)
end

if ( ! File.file?("#{keyfileloc}"))
    puts "Key file #{keyfileloc} does not exist"
    usage(5)
end

input = File.read('nodes/nodetemplate.json')
eruby = Erubis::Eruby.new(input)
json = File.read("deployments/conf/#{dname}.json")
depl = JSON.parse(json)

depl['nodes'].each() do |node|
  node['roles'].each do |role|
		if role == roleid 
			cmdstring="xterm  -e ssh -l #{userid} -i #{keyfileloc} #{node['ip']}"
			pid = spawn cmdstring
			Process.detach(pid)
		end
	end
end

